<?php
namespace App\Repositories;

use App\Enums\RewardEnum;
use App\Enums\TaskEnum;
use App\Exceptions\BasicException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class TaskRepository
{

    /**
     * 新增
     * @param $param
     * @return bool
     * @throws BasicException
     */
    public function addModule($param) {
        $addConfig = app('model_task_module')->create($param);

        if ($addConfig) {
            $this->clearModuleCache();
            return $addConfig;
        }
        throw new BasicException(93045);
    }

    /**
     * 删除
     */
    public function delModule($idArr = []) {
        $res = app('model_task_module')->whereIn("id", $idArr)->delete();

        if ($res) {
            $this->clearModuleCache();
            return $res;
        }
        throw new BasicException(93044);
    }

    /**
     * 修改
     */
    public function saveModule($where,$param) {
        $saveConfig = app('model_task_module')->where($where)->update($param);

        if ($saveConfig!==false){
            $this->clearModuleCache();
            return true;
        }
        throw new BasicException(93047);
    }

    /**
     * 单条
     */
    public function getModule($where) {
        $result = app('model_task_module')->where($where)->first();

        return $result;
    }

    /**
     * 管理员后台查询配置数据
     */
    public function getModuleQueryList(Array $params) {
        $whereArr = [];

        $whereFunc = function ($query) use ($params) {
        };

        $page = empty($params['page']) ? 1 : $params['page'];
        $perPage = empty($params['perPage']) ? 10 : $params['perPage'];

        $result = app('model_task_module')->where($whereArr)->where($whereFunc)->orderBy('id','desc')->paginate($perPage, ['*'], '', $page);

        return $result;
    }

    /**
     * 新增
     * @param $param
     * @return bool
     * @throws BasicException
     */
    public function addType($param) {
        $addConfig = app('model_task_type')->create($param);

        if ($addConfig) return $addConfig;
        throw new BasicException(93045);
    }

    /**
     * 删除
     */
    public function delType($idArr = []) {
        $res = app('model_task_type')->whereIn("id", $idArr)->delete();

        if ($res) return $res;
        throw new BasicException(93044);
    }

    /**
     * 修改
     */
    public function saveType($where,$param) {
        $saveConfig = app('model_task_type')->where($where)->update($param);

        if ($saveConfig!==false) return true;
        throw new BasicException(93047);
    }

    /**
     * 单条
     */
    public function getType($where) {
        $result = app('model_task_type')->where($where)->first();

        return $result;
    }

    /**
     * 管理员后台查询配置数据
     */
    public function getTypeQueryList(Array $params) {
        $whereArr = [];

        $whereFunc = function ($query) use ($params) {
            if (!empty($params["name"])) {
                $query->where('name', 'like', "%" . $params['name'] . "%");
            }
        };
        if (!empty($params["status"])) {
            $whereArr[] = ["link_status", "=", $params["status"]];
        }

        $page = empty($params['page']) ? 1 : $params['page'];
        $perPage = empty($params['perPage']) ? 10 : $params['perPage'];

        $result = app('model_task_type')->where($whereArr)->where($whereFunc)->orderBy('id','desc')->paginate($perPage, ['*'], '', $page);

        foreach ($result as $item) {
            $item->link_type_name = empty(TaskEnum::TASK_LINK_NAME_MAP[$item->link_type]) ? "未知跳转类型" : TaskEnum::TASK_LINK_NAME_MAP[$item->link_type];
        }

        return $result;
    }

    /**
     * 新增
     * @param $param
     * @return bool
     * @throws BasicException
     */
    public function addConfig($param) {
        $addConfig = app('model_task_config')->create($param);

        if ($addConfig) {
            $this->clearConfigCache();
            return $addConfig;
        }
        throw new BasicException(93045);
    }

    /**
     * 删除
     */
    public function delConfig($idArr = []) {
        $res = app('model_task_config')->whereIn("id", $idArr)->delete();

        if ($res) {
            $this->clearConfigCache();
            return $res;
        }
        throw new BasicException(93044);
    }

    /**
     * 修改
     */
    public function saveConfig($where,$param) {
        $saveConfig = app('model_task_config')->where($where)->update($param);

        if ($saveConfig) {
            $this->clearConfigCache();
            return $saveConfig;
        }
        throw new BasicException(93047);
    }

    /**
     * 单条
     */
    public function getConfig($where) {
        $result = app('model_task_config')->where($where)->first();

        return $result;
    }

    /**
     * 管理员后台查询配置数据
     */
    public function getConfigQueryList(Array $params) {
        $whereArr = [];
        $whereArr[] = ["t1.is_deleted", "=", 0];
        $whereFunc = function ($query) use ($params) {
        };

        $page = empty($params['page']) ? 1 : $params['page'];
        $perPage = empty($params['perPage']) ? 10 : $params['perPage'];

        $taskConfigModel = app('model_task_config');
        $taskTypeModel = app('model_task_type');
        $taskModuleModel = app('model_task_module');
        $rewardModel = app('model_reward');

        // 模塊搜索
        if (!empty($params["type"])) {
            $whereArr[] = ["t3.id", "=", $params["type"]];
        }
        // 名称搜索
        if (!empty($params["name"])) {
            $whereFunc = function ($query) use ($params) {
                if (!empty($params["name"])) {
                    $query->where('t1.name', 'like', "%" . $params['name'] . "%");
                }
            };
        }

        $result = app('model_task_user')
            ->from($taskConfigModel->getTable() . " as t1")
            ->select([
                "t1.*",
                DB::raw("t4.name as reward_bag_name"),
                DB::raw("t5.name as reward_item_name"),
                DB::raw("t2.name as task_type_name"),
                DB::raw("t3.name as task_module_name"),
            ])
            ->leftJoin(DB::raw($taskTypeModel->getTable() . " as t2"), "t1.type_id", "=", "t2.id")
            ->leftJoin(DB::raw($taskModuleModel->getTable() . " as t3"), "t1.module_id", "=", "t3.id")
            ->leftJoin(DB::raw($rewardModel->getTable() . " as t4"), "t1.reward_id", "=", "t4.id")
            ->leftJoin(DB::raw("ln_reward_item as t5"), "t1.reward_id", "=", "t5.id")
            ->where($whereArr)->where($whereFunc)->orderBy('t1.id','desc')->paginate($perPage, ['*'], '', $page);

        foreach ($result as $item) {
            $item->task_type_name = empty($item->task_type_name) ? "未知类型" : $item->task_type_name;
            $item->task_module_name = empty($item->task_module_name) ? "未知模块" : $item->task_module_name;
            if ($item->reward_type == RewardEnum::REWARD_BIG_TYPE_ITEM) {
                $item->reward_name = empty($item->reward_item_name) ? "未知道具奖品" : $item->reward_item_name;
            } else {
                $item->reward_name = empty($item->reward_bag_name) ? "未知礼包奖品" : $item->reward_bag_name;
            }
        }

        return $result;
    }

    public function clearModuleCache() {
        foreach (TaskEnum::TASK_MODULE_LIST as $moduleId) {
            $redisKey = sprintf(TaskEnum::TASK_MODULE, $moduleId);
            Redis::del($redisKey);
        }
    }

    public function clearConfigCache() {
        foreach (TaskEnum::TASK_MODULE_LIST as $moduleId) {
            $redisKey = sprintf(TaskEnum::TASK_CONFIG, $moduleId);
            Redis::del($redisKey);
        }
    }

}